package com.stox.repository.file.iterator;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.stox.dto.enumeration.SpanType;
import com.stox.model.Bar;
import com.stox.repository.file.AbstractFileRepository.EntityIterator;

public abstract class SpanTypeAwareBarIterator implements EntityIterator<Bar> {
	
	private int value = -1;
	private Bar higherBar = null;
	private List<Bar> bars = new ArrayList<Bar>();
	private Calendar calendar = Calendar.getInstance();
	
	private SpanType spanType;

	public List<Bar> getBars() {
		return bars;
	}
	
	@Override
	public boolean shouldContinue(Bar entity) {
		merge(entity);
		return true;
	}
	
	private void merge(Bar bar){
		if(SpanType.DAILY.equals(spanType)){
			bars.add(bar);
			return;
		}
		calendar.setTime(bar.getDate());
		if(value != calendar.get(spanType.getUnit())){
			higherBar = new Bar();
			higherBar.setHigh(Double.MIN_VALUE);
			higherBar.setLow(Double.MAX_VALUE);
			higherBar.setOpen(bar.getOpen());
			higherBar.setDate(bar.getDate());
			bars.add(higherBar);
			value = calendar.get(spanType.getUnit());
		}
		
		if(bar.getHigh() > higherBar.getHigh()){
			higherBar.setHigh(bar.getHigh());
		}
		if(bar.getLow() < higherBar.getLow()){
			higherBar.setLow(bar.getLow());
		}
		higherBar.setClose(bar.getClose());
		higherBar.setVolume(bar.getVolume() + higherBar.getVolume());
	}
	
	public void setSpanType(SpanType spanType) {
		this.spanType = spanType;
	}
	
}
